FAQ Page

867

IL WEB

  • Django: codice esempio

    DJANGO BIGINO   18-08-2023

    - Installare Python scaricarlo da Browser
    - Installare Django scaricarlo da Browser
    - Installare Anaconda scaricarlo da Browser
      .conda activate portfolio
      .pip install django
    - Cd porfolio
    - django-admin startproject personal_portfolio  (crea progetto)
    - cd personal_portfolio                         (entrare nella cartella dove c'è manage.py e lanciare runserver)
    - Python manage.py runserver
    - python manage.py startapp hello_word          (crea app)
    - python manage.py makemigrations               (creare database e tabelle)
    - python manage.py migrate                      (crea collegamento database in admin)
    - Nel file settings.py aggiungere Import os     (serve per interagire col sistema operativo WINDOWS etc.)
      .Nella classe INSTALLED_APPS aggiungere nome App es: "hello_word",
      .Nella sezione sotto mettere la cartella static dove metteremo immagini etc STATIC_URL="static/"
        Static files (CSS, JavaScript, Images)
         # nel file setting.py aggiungere queste righe
           STATIC_URL = '/static/'
           STATIC_ROOT = '/static/'
           STATICFILES_DIRS = [
              os.path.join(BASE_DIR, 'static')
              ]
      .Nella sezione Path aggiungere il path della cartella media
         # Build paths inside the project like this: BASE_DIR / 'subdir'.
           BASE_DIR = Path(__file__).resolve().parent.parent
           MEDIA_URL = '/media/'
           MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    - Aprire admin.py e inserire il codice per visualizzare il database
           from django.contrib import admin
           from .models import Document
           from .models import Author, Category, Journal

           admin.site.register(Document)
           admin.site.register(Author)
           admin.site.register(Category)
           admin.site.register(Journal)

    - python manage.py collectstatic               (collega la cartella STATIC ALL ROOT)




    #############################   VIEW esempio di passaggio valori  ##################################

    from . import models
    from django.shortcuts import render, redirect

    def uploadFile(request):
        if request.method == "POST":
            # Fetching the form data
            fileTitle = request.POST["fileTitle"]
            uploadedFile = request.FILES["uploadedFile"]

            # Saving the information in the database
            document = models.Document(
                title = fileTitle,
                uploadedFile = uploadedFile
            )
            document.save()
            
        documents = models.Document.objects.all()

        return render(request, "Core/upload-file.html", context = {                    # ritorna un dizionario
            "files": documents
        })



    def index(request):                                                                # CODICE INSEGNANTE
        message = ''
        if request.method == 'POST':
            f_name = request.POST['f_name']
            email = request.POST['email']
            message = request.POST['message']
            #return redirect("Core/index.html")
            message = message + email + f_name

        return render(request,"Core/index.html",{'sum': message})                      # ritorna una stringa di valori
     



    #############################   DATABASE  ##################################

    ------RELAZIONE MOLTI A MOLTI-----  provato funziona


    ricordarsi che bisogna registrare le tabelle nell ADMIN.PY

    from django.db import models

     
        
    class Publication(models.Model):
        title = models.CharField(max_length=30)
        class Meta:
            ordering = ['title']

        def __str__(self):
            return self.title

    class Article(models.Model):
        headline = models.CharField(max_length=100)
        descrizione = models.CharField(max_length=100)
        publications = models.ManyToManyField(Publication)

        class Meta:
            ordering = ['headline']

        def __str__(self):
            return self.headline

    ------RELAZIONE MOLTI A UNO-----  provato funziona -----  provato funziona ---- esercizio dottori

    *****Urls.py**************
    from django.contrib import admin
    from django.urls import path
    from . import views

    urlpatterns = [
        path("", views.save_data),
       ]


    *****Models.py**************
    from django.db import models
    #from countries.moodels import Country
    # Create your models here.


    class regioni(models.Model):
        descrizione_regione= models.CharField(max_length=60)
        def __str__(self):
            return self.descrizione_regione
       

     

    *****View.py**************
    from django.shortcuts import render,redirect
    from .models import regioni, comuni, dottori
    from django.http import HttpResponseRedirect
    # Create your views here.

    def save_data(request):
        if request.method == 'POST':
            field1_value = request.POST['descrizione_regione']
            # Create an instance of your model and save it to the database
            regioni.objects.create(descrizione_regione=field1_value)                  # crea un record nuovo con il dato del form
            
            # Redirect to a success page or another view
            return HttpResponseRedirect(request.path_info)                            # ritorna alla pagina da cui è partita l'operazione
            #return redirect('input')
        
        
        
        return render(request, 'index.html')


    def save_comuni(request):
        if request.method == 'POST':
            field1_value = request.POST['descrizione_comuni']
            # Create an instance of your model and save it to the database
            comuni.objects.create(descrizione_comune=field1_value)
            
            # Redirect to a success page or another view
            return HttpResponseRedirect(request.path_info)
            #return redirect('input')
           
        
        return render(request, 'comuni.html')


    def save_dottori(request):
        if request.method == 'POST':
            field1_value = request.POST['descrizione_dottore']
            # Create an instance of your model and save it to the database
            dottori.objects.create(descrizione_dottori=field1_value)

            field2_value = request.POST['name']
            dottori.objects.create(name=field2_value)

            field3_value = request.POST['country']
            dottori.objects.create(country=field3_value)

            field4_value = request.POST['telefono']
            dottori.objects.create(telefono=field4_value)
            
            # Redirect to a success page or another view
            return HttpResponseRedirect(request.path_info)
            #return redirect('input')
           
        
        return render(request, 'dottori.html')



    ------RELAZIONE MOLTI A UNO -----  provato funziona ---- esercizio regioni combo dinamica HTMX


    from django.db import models

    class Country(models.Model):
        name = models.CharField(max_length=50)

        def __str__(self):
            return self.name

    class City(models.Model):
        name = models.CharField(max_length=50)
        country = models.ForeignKey(Country, on_delete=models.CASCADE)
        
        def __str__(self):
            return self.name
     
    class cantine(models.Model):
       
        name = models.CharField(max_length=100)
        descrizione_cantine = models.CharField(max_length=500)
        telefono = models.IntegerField()
        comune=models.ForeignKey(City,on_delete = models.CASCADE)
       # country = models.ForeignKey(Country,on_delete=models.CASCADE)
        def __str__(self):
            return self.name


    #############  VIEW COLLLEGATA AL MODELLO QUI SOPRA ###########

    from django.shortcuts import render

    from .forms import LocationForm
    from .models import City 

    def index(request):
        if request.method == "POST":
            form = LocationForm(request.POST)
            if form.is_valid():
                print(form.cleaned_data["country"])
                print(form.cleaned_data["city"])
            else:
                print(form.errors)
        else:
            form = LocationForm()
        return render(request, 'index.html', {"form": form})

    def load_cities(request):
        country_id = request.GET.get("country")
        cities = City.objects.filter(country_id=country_id)


    #############  FORM COLLLEGATA AL MODELLO QUI SOPRA ###########

    from django import forms 

    from .models import Country, City 

    class LocationForm(forms.Form):
        country = forms.ModelChoiceField(queryset=Country.objects.all(),
            widget=forms.Select(attrs={"hx-get": "load_cities/", "hx-target": "#id_city"}))
        city = forms.ModelChoiceField(queryset=City.objects.none())

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)

            if "country" in self.data:
                country_id = int(self.data.get("country"))
                self.fields["city"].queryset = City.objects.filter(country_id=country_id)
         
    #############  fine                                 ###########







    ------RELAZIONE MOLTI A UNO -----  provato funziona ---- esercizio con form con filtri
    *****Urls.py**************

    from . import views
    from django.urls import path
    from django.conf import settings
    from django.conf.urls.static import static

    app_name = "Core1"

    urlpatterns = [
        path("", views.uploadFile, name = "uploadFile"),
        path('lista', views.index, name = 'index'),
        path('bootstrap', views.BootstrapFilterView, name = 'bootstrap_form'),
      
    ]

    if settings.DEBUG: 
        urlpatterns += static(
            settings.MEDIA_URL, 
            document_root = settings.MEDIA_ROOT
        )

    *****Models.py**************

    from django.db import models


    class Student(models.Model):
        title1 = models.CharField(max_length=120)
        
        publish_date1 = models.DateTimeField()
        views1 = models.IntegerField(default=0)
        reviewed1 = models.BooleanField(default=False)

        def __str__(self):
            return self.title1

    class Document(models.Model):
        title = models.CharField(max_length = 200)
        
        uploadedFile = models.FileField(upload_to = "Uploaded Files/")
        dateTimeOfUpload = models.DateTimeField(auto_now = True)

      
    def __str__(self):
            return self.title

    # Create your models here.
    class Author(models.Model):
        name = models.CharField(max_length=30)

        def __str__(self):
            return self.name


    class Category(models.Model):
        name = models.CharField(max_length=20)

        def __str__(self):
            return self.name


    class Journal(models.Model):
        title = models.CharField(max_length=120)
        author = models.ForeignKey(Author, on_delete=models.CASCADE)
        categories = models.ManyToManyField(Category)
        publish_date = models.DateTimeField()
        views = models.IntegerField(default=0)
        reviewed = models.BooleanField(default=False)

        def __str__(self):
            return self.title

    #############  VIEW COLLLEGATA AL MODELLO QUI SOPRA ###########
    *****View.py**************
    from django.http import JsonResponse
    from time import sleep

    from django.db.models import Q, Count
    from django.shortcuts import render, get_object_or_404
    from . import models
    from .models import Journal, Category

    def is_valid_queryparam(param):

     return param != '' and param is not None



    def uploadFile(request):
        if request.method == "POST":
            # Fetching the form data
            fileTitle = request.POST["fileTitle"]
            uploadedFile = request.FILES["uploadedFile"]

            # Saving the information in the database
            document = models.Document(
                title = fileTitle,
                uploadedFile = uploadedFile
            )
            document.save()
            
        documents = models.Document.objects.all()

        return render(request, "Core/upload-file.html", context = {
            "files": documents
        })

    def index(request):
        a = 15
        b = 10
      
        return render(request,"Core/index.html",{'sum': a,'sub':  b})


    def BootstrapFilterView(request):
         
        qs = Journal.objects.all()
        #categories= Category.objects.all()    SELEZIONA TUTTI I RECORD
        #categories= Category.objects.filter(name__icontains="Lombardia").filter(name__icontains="Toscana")  per il filtro AND
        #categories= Category.objects.filter(Q(name__icontains="Lombardia") | Q(name__icontains="Toscana"))      per il filtro OR
        #categories= Category.objects.filter(Q(name__icontains="Lombardia") & Q(name__icontains="Lombardia"))     per il filtro AND

        categories= Category.objects.filter(Q(name__icontains="Lombardia") | Q(name__icontains="Toscana"))     
        
         
      
        title_contains_query = request.GET.get('title_contains')
        title_or_author_query = request.GET.get('title_or_author')
        id_exact_query = request.GET.get('id_exact')

        

        
        category = request.GET.get('category')
        
        if is_valid_queryparam(title_contains_query):
            qs = qs.filter(title__icontains=title_contains_query)

        elif is_valid_queryparam(id_exact_query):
            qs = qs.filter(id=id_exact_query)

        elif is_valid_queryparam(title_or_author_query):
            qs = qs.filter(Q(title__icontains=title_or_author_query)
                           | Q(author__name__icontains=title_or_author_query)
                           ).distinct()
            
        if is_valid_queryparam(category) and category != 'Choose...':
            qs = qs.filter(categories__name=category)
        

        context = {
            'queryset': qs,
            'categories': categories,
               
             
        }

        return render(request, "Core/bootstrap_form.html", context)

    #############      FINE                             ###############################
     

  • Rif. 867